/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.rocketmq.example.simple.Producer;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

//简单样例：同步发送消息
public class Producer {
    public static void main(String[] args) throws MQClientException, InterruptedException {
        //实例化消息生产者 Producer对象
        DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");
        //设置 Namesrv地址，如果环境变量配置了，这里可以不配置
        producer.setNamesrvAddr("192.168.23.201:9876;192.168.23.203:9876;192.168.23.204:9876");
        //这里不设置超时时间，会报错：sendDefaultImpl call timeout
        producer.setSendMsgTimeout(10000);
        //启动 Producer实例
        producer.start();
        for (int i = 0; i < 20; i++)
            try {
                {
                    //创建消息，并指定 Topic、Tag、key、消息体
                    Message msg = new Message("TopicTest",
                            "TagA",
                            "OrderID188",
                            "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
                    //同步传递消息，消息会发给集群中的一个Broker节点,返回发送结果
                    SendResult sendResult = producer.send(msg);
                    System.out.printf("%s%n", sendResult);

                    //发送单向消息，没有任何返回结果
                    //producer.sendOneway(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        //如果不在发送消息，则关闭 producer实例
        System.out.println("消息发送完成...");
        producer.shutdown();
    }
}
